<template>
  <div class="simulationMain">
    <div class="questionWrap"
         v-if="questionList.length"
         :class='{"hide":lastQuestion||showQuestion}'>
      <div class="question">
        <div class="questionNum">
          <p class="p1"> 第{{index+1}}题 </p>
          <span style="float:right">{{index+1}}/{{questionList.length}}</span>
        </div>
        <div class="questionContent">
          <div class="questionTitle">
            {{questionList.length&&questionList[index].question}}
          </div>
          <div class="questionAnswer"
               :data-answer=questionList.length&&questionList[index].answerkey>
            <div v-for="(value,key) in questionList.length&&answer_list"
                 :key=key>
              <p @click.stop="choise(index,key,questionList[index].id)"
                 :class='{"right":questionList[index].res ==key}'>
                <span>{{options[key]}}</span>
                {{value}}
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class="questionBtn">
        <span class="prev"
              @click.stop="prevQuestion"
              :class='{"disabled": index==0}'
              :disabled='index==0'>上一题</span>

        <span class="next"
              :class='{"disabled":! MultiSelection[index].active}'
              @click.stop="nextQuestion(index)">下一题</span>
      </div>
    </div>
    <div v-if="noData"
         class="noData">
      <img :src=noDataPng>
    </div>
    <div class="timeOver"
         v-if="showTimeData">
      <div class="imgOver slideInDown animated"
           :animation="animationData">
        <img :src=img>
        <span class="confirmBtn"
              @click.stop="confirm">确定</span>
      </div>
    </div>
    <div class="markBottom"
         :class='{"hide": lastQuestion}'>
      <p class="iconfont icon-timer">
        <span>{{startHour}}:{{startMin}}:{{startSecond}}</span>
      </p>
      <p>
        <button class="iconfont  icon-share2"
                open-type="share"></button>
      </p>
    </div>
  </div>
</template>
  <script>
import { mapState, mapMutations } from 'vuex'
import { formatTime } from '@/utils'
export default {
  data () {
    return {
      index: 0,
      lastQuestion: false,
      showQuestion: false,
      startTimeStamp: 0,
      showTimeData: false,
      startSecond: 0,
      startMin: 0,
      startHour: 0,
      timer: null,
      commitAnswer: [],
      examRecord: [],
      commitItem: -1, // 试卷的某一道题
      examPaperId: -1, // 选择考卷的id
      showBottom: false, // 最后一页 隐藏底部工具
      clickAnswer: '',
      showmenuMain: false, // 展示菜单页面
      MultiSelection: [], // 答题选项
      currentIndex: -1,
      commitKey: '',
      count: 0,
      rightTotal: 0,
      totalTime: '',
      rightAnswerArray: [],
      questionList: [],
      options: ['A', 'B', 'C', 'D'],
      user_answer_list: [],
      error_list: [],
      noDataPng: 'https://dati.co-links.com/static/xadmin/images/noData.png',
      examBg: 'https://dati.co-links.com/static/xadmin/images/examBg.png',
      testpaperId: -1,
      noData: false,
      img: 'https://dati.co-links.com/static/xadmin/images/timeUp.png',
      longTime: 3600,
      beginHours: 0,
      beginMin: 0,
      beginSecond: 0,
      totalTime: 0
    }
  },
  onShareAppMessage (options) {
    return {
      title: '答题',
      path: '/pages/index/main'
    }
  },
  computed: {
    ...mapState({
      device: state => state.device,
      randomRecord: state => state.randomRecord,
      formalRecord: state => state.formalRecord,
      userInfo: state => state.userInfo,
      width: state => state.device.width,
      height: state => state.device.height
    }),
    height () {
      return this.device.height
    },
    showExamOver () {
      if (this.showmenuMain || this.showQuestion) {
        return 'hide'
      } else if (this.lastQuestion) {
        return 'show'
      } else {
        return ''
      }
    },
    answer_list () {
      let that = this
      return that.questionList.length && Object.keys(that.questionList[that.index].answer_list).map(key => that.questionList[that.index].answer_list[key]).sort((a, b) => {
        return a.localeCompare(b)
      })
    }
  },
  methods: {
    ...mapMutations(['setExamPaper', 'setrandomRecord', 'setformalRecord', 'setExamResult', 'setUserInfo']),
    choise (index, key, id) {
      console.log(index, key, id)
      if (key === this.options.indexOf(this.questionList[index].answerkey)) {
        this.user_answer_list.push({
          id: id,
          res: this.options.indexOf(this.questionList[index].answerkey)
        })
        this.user_answer_list = this.arrayUnique2(this.user_answer_list, 'id')
      } else {
        this.error_list.push({
          id: id,
          res: key,
          index: index
        })
        this.error_list = this.arrayUnique2(this.error_list, 'id')
      }
      this.questionList[index].hide = false
      this.clickAnswer = this.options[key]
      // 当前答的是哪一道题

      // this.commitAnswer.push({
      //   index: index,
      //   id: this.questionList[index].id,
      //   res: key,
      //   right: this.commitKey === this.options.indexOf(this.questionList[this.index].answer) ? 1 : 0
      // })
      this.commitAnswer = this.arrayUnique2(this.commitAnswer, 'id')
      this.questionList[index].res = key
      this.questionList[index].rightNum2 = this.answer_list.indexOf(this.questionList[index].answerkey)
      this.currentIndex = index
      this.commitKey = key
      this.rightAnswerArray[index] = this.options.indexOf(this.questionList[index].answerkey)
      this.rightAnswer = this.questionList[index].rightNum
      this.commitAnswer[index] = {
        index: index,
        id: this.questionList[index].id,
        res: key,
        right: this.commitKey === this.options.indexOf(this.questionList[this.index].answerkey) ? 1 : 0
      }
      console.log(this.commitKey)
      console.log(this.options.indexOf(this.questionList[this.index].answerkey))
      console.log(this.commitAnswer)
      for (var k = 0; k < this.commitAnswer.length; k++) {
        this.MultiSelection[index].active = true
      }
    },
    nextQuestion (index) {
      let that = this
      if (!this.MultiSelection[index].active) {
        return
      }
      if (this.index === this.questionList.length - 1) {
        console.log(this.commitAnswer)
        this.totalTime = this.beginHours * 3600 + this.beginMin * 60 + this.beginSecond * 1 - this.startHour * 3600 - this.startMin * 60 - this.startSecond * 1
        for (var i = 0; i < this.commitAnswer.length; i++) {
          if (this.commitAnswer[i].right) {
            this.rightTotal++
          }
        }
        // 提交后台的数据
        this.setExamPaper({
          rightTotal: this.rightTotal,
          time: this.totalTime,
          totalNum: this.questionList.length,
          startHour: parseInt(this.totalTime / 3600),
          startMin: parseInt((this.totalTime - parseInt(this.totalTime / 3600) * 3600) / 60),
          startSecond: this.totalTime - parseInt(this.totalTime / 3600) * 3600 - parseInt((this.totalTime - parseInt(this.totalTime / 3600) * 3600) / 60) * 60
        })
        this.$http.post('https://dati.co-links.com/exam/recording/', {
          userid: that.userid,
          special_id: that.userInfo.special_id,
          effect: parseInt(that.rightTotal / that.questionList.length * 100),
          longtime: that.totalTime
        }).then((res) => {
          console.log(res.data.data.grade)
          console.log(parseInt(this.rightTotal / this.questionList.length * 100))
          that.setExamResult({
            grade: parseInt(that.rightTotal / that.questionList.length * 100),
            correct_num: this.rightTotal
          })
          console.log(res)
          wx.redirectTo({
            url: '../tranScore/main'
          })
        })
      } else {
        // 设置currentIndex  8/18
        this.currentIndex = this.index
        if (this.commitKey === '') {
          this.commitKey = this.questionList[index].res
        }
        this.commitAnswer[this.currentIndex] = {
          index: this.currentIndex,
          id: this.questionList[this.currentIndex].id,
          res: this.commitKey,
          right: this.commitKey === this.options.indexOf(this.questionList[this.currentIndex].answerkey) ? 1 : 0
        }
        this.commitKey = ''
        console.log(this.commitAnswer)
        // this.setExamPaper({
        //   clickArray: this.commitAnswer
        // })
        this.index++
      }
    },
    // 计时
    fill_zero_prefix (num) {
      return num < 10 ? '0' + num : num
    },
    startCountTime () {
      let that = this
      that.timer = null
      that.timer = setInterval(function () {
        if (that.startHour * 1 === 0 && that.startMin * 1 === 0 && that.startSecond * 1 === 0) {
          clearInterval(that.timer)
          that.showTimeData = true
          return false
        }
        if (that.startSecond * 1 === 0) {
          if (that.startSecond * 1 === 0 && that.startMin * 1 === 0) {
            that.startMin = 59
            that.startHour = that.fill_zero_prefix(that.startHour * 1 - 1)
          } else {
            if (that.startMin && that.startSecond * 1 === 0) {
              console.log(that.startMin)
              that.startMin = that.fill_zero_prefix(that.startMin * 1 - 1)
            }
          }
          that.startSecond = 60
        }
        that.startSecond = that.fill_zero_prefix(that.startSecond * 1 - 1)
      }, 1000)
    },
    arrayUnique2 (arr, name) {
      let hash = {}
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
        return item
      }, [])
    },
    prevQuestion () {
      if (this.index === 0) {
        return false
      } else {
        this.index--
      }
    },
    confirm () {
      let that = this
      this.totalTime = this.beginHours * 3600 + this.beginMin * 60 + this.beginSecond * 1 - this.startHour * 3600 - this.startMin * 60 - this.startSecond * 1
      console.log(this.commitAnswer)
      for (var i = 0; i < this.commitAnswer.length; i++) {
        if (this.commitAnswer[i].right) {
          this.rightTotal++
        }
      }
      // 提交后台的数据
      this.setExamPaper({
        rightTotal: this.rightTotal,
        time: this.totalTime,
        totalNum: this.questionList.length,
        startHour: parseInt(this.totalTime / 3600),
        startMin: parseInt((this.totalTime - parseInt(this.totalTime / 3600) * 3600) / 60),
        startSecond: this.totalTime - parseInt(this.totalTime / 3600) * 3600 - parseInt((this.totalTime - parseInt(this.totalTime / 3600) * 3600) / 60) * 60
      })
      this.$http.post('https://dati.co-links.com/exam/recording/', {
        userid: that.userid,
        special_id: that.userInfo.special_id,
        effect: that.rightTotal / that.questionList.length * 100,
        longtime: that.totalTime
      }).then((res) => {
        // console.log(res)
        console.log(res.data.data.grade)
        // console.log(res.data.data.grade)
        // console.log(this.rightTotal)
        // console.log(this.questionList.length)
        console.log(parseInt(this.rightTotal / this.questionList.length * 100))
        that.setExamResult({
          grade: res.data.data.grade || parseInt(this.rightTotal / this.questionList.length * 100),
          correct_num: that.rightTotal
        })
        console.log(res)
        wx.redirectTo({
          url: '../tranScore/main'
        })
      }).catch((res) => {
        console.log(res)
        wx.redirectTo({
          url: '../tranScore/main'
        })
      })
    },
    init () {
      let that = this
      this.userid = this.userInfo.user_id || wx.getStorageSync('user_id')
      wx.showLoading({
        title: '加载中'
      })
      this.$http.get('https://dati.co-links.com/exam/paper/', {
        uid: that.userid
      }).then((res) => {
        that.setUserInfo({
          special_id: res.data.data.id
        })
        that.startHour = that.fill_zero_prefix(parseInt(res.data.data.long_time / 3600))
        that.beginHours = that.startHour
        that.startMin = that.fill_zero_prefix(parseInt((res.data.data.long_time - that.startHour * 1 * 3600) / 60))
        that.beginMin = that.startMin
        that.startSecond = that.fill_zero_prefix(res.data.data.long_time - that.startHour * 3600 - that.startMin * 60)
        that.beginSecond = that.startSecond
        that.questionList = res.data.data.questions
        if (res.data.data.questions.length === 0) {
          that.noData = true
        }
        if (that.questionList.length > 0) {
          wx.hideLoading()
          clearInterval(that.timer)
          that.startCountTime()
        }
        // console.log(that.questionList[0].collection)
        for (var i in that.questionList) {
          that.questionList[i].res = -1
          that.questionList[i].hide = true
        }
        that.MultiSelection = []
        // that.examPaperId = that.$mp.query.id
        that.index = 0
        for (var m = 0; m < that.questionList.length; m++) {
          that.MultiSelection.push({
            active: false
          })
        }
        console.log(this.questionList)
      })
    }
  },
  mounted () {
    this.init()
    this.commitAnswer = []
    this.rightAnswerArray = []
    this.noData = false
    // this.questionList = []
    this.showmenuMain = false
    this.lastQuestion = false
    this.showQuestion = false
    this.count = 0

    if (this.startHour === 0) {
      this.startHour = '0' + this.startHour
    }
    if (this.startMin === 0) {
      this.startMin = '0' + this.startMin
    }
    if (this.startSecond === 0) {
      this.startSecond = '0' + this.startSecond
    }
    this.MultiSelection = []
    // this.examPaperId = this.$mp.query.id
    this.index = 0
    if (this.formalRecord.finishStatus === 1) {
      // 试卷已提交  清空之前的状态
      this.lastQuestion = false
      this.showQuestion = false
      this.showmenuMain = false
      this.lastQuestion = false
      this.rightTotal = 0
      this.startSecond = '00'
      this.startMin = '00'
      this.startHour = '00'
      for (let i = 0; i < this.questionList.length; i++) {
        this.questionList[i].res = -1
      }
    }
  },
  onUnload () {
    console.log('onUnload')
    clearInterval(this.timer)
    this.confirm()
  }

}
</script>
 <style >
.simulationMain {
  height: 100%;
}
.question {
  padding: 0 32rpx;
  margin-bottom: 20rpx;
  background: white;
}
.question .questionNum {
  font-size: 30rpx;
  color: #333;
  height: 98rpx;
  line-height: 98rpx;
  border-bottom: 2rpx solid #e6e6e6;
}
.question .questionNum p {
  display: inline-block;
}
.question .questionNum .p2 {
  float: right;
  width: 112rpx;
}
.question .questionNum .p2 span {
  display: inline-block;
  width: 112rpx;
  height: 46rpx;
  background: #febd32;
  color: white;
  font-size: 26rpx;
  text-align: center;
  line-height: 46rpx;
  border-radius: 6rpx;
  -webkit-border-radius: 6rpx;
}
.question .questionTitle {
  font-size: 32rpx;
  color: #333333;
  padding: 20rpx 0;
}

.questionContent {
  padding-bottom: 30rpx;
}
.questionAnswer p {
  font-size: 32rpx;
  color: #666666;
  padding: 18rpx 0;
  padding-left: 30rpx;
}
.questionAnswer p span {
  display: inline-block;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  margin-right: 30rpx;
  border: 1px solid #a5a5a5;
  text-align: center;
  line-height: 48rpx;
}
.questionAnswer p.active {
  color: #ef5151;
}
.questionAnswer p.right {
  color: #00cc76;
}
.questionAnswer p.right span {
  background: #00cc76;
  color: #fff;
  border: 1px solid #00cc76;
}
.questionAnswer p.active span {
  border: 1px solid #ef5151;
  background: #ef5151;
  color: white;
}
.markBottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 90rpx;
  border-top: 2rpx solid #e6e6e6;
  background: white;
  text-align: center;
}
.markBottom p {
  display: inline-block;
  width: 25%;
  height: 100%;
  line-height: 90rpx;
  font-size: 50rpx;
  color: #333;
  text-align: center;
}
.markBottom p span {
  display: inline-block;
  font-size: 28rpx;
  margin-left: 10rpx;
  line-height: 90rpx;
  height: 100%;
  vertical-align: top;
}
.examOver {
  text-align: center;
  display: none;
}

.examBg {
  width: 242rpx;
  height: 224rpx;
  padding-top: 180rpx;
}

.tips {
  text-align: center;
  font-size: 32rpx;
  color: #333333;
  padding-top: 50rpx;
}

.questionBtn {
  text-align: center;
  position: fixed;
  bottom: 50rpx;
  left: 0;
  width: 100%;
  height: 80rpx;
  margin-bottom: 100rpx;
}
.questionBtn span,
.questionBtn button {
  display: inline-block;
  width: 210rpx;
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  border-radius: 10rpx;
  -webkit-border-radius: 10rpx;
  border: 2rpx solid #00cc76;
  font-size: 28rpx;
  color: #00cc76;
}
.questionBtn .next {
  background: #00cc76;
  color: white;
  margin-left: 88rpx;
}
.questionBtn .disabled {
  background: #ccc;
  color: white;
  border: 2rpx solid #ccc;
}
.questionBtn .nextBtn {
  display: none;
}
.hide {
  display: none !important;
}

.show {
  display: block;
}

.questionBtn .show {
  display: inline-block;
}

.markBottom .collectActive {
  color: #ef5151;
}

.menuMain {
  background: #f7f7f7;
  display: none;
}

.menuMain.showmenuMain {
  display: block;
}

.singleSelection,
.MultiSelection,
.checkSelection {
  padding: 0 32rpx;
  margin-bottom: 20rpx;
  background: white;
}
.MultiSelection .title {
  padding-top: 20rpx;
  font-size: 32rpx;
  color: #333333;
}
.topicSelect {
  padding-bottom: 100rpx;
}

.fixedBtn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  height: 88rpx;
  border-top: 1px solid #e6e6e6;
  background: white;
}
.fixedBtn span {
  display: inline-block;
  margin-top: 8rpx;
  width: 292rpx;
  height: 72rpx;
  text-align: center;
  line-height: 72rpx;
  color: #ffffff;
  font-size: 28rpx;
  border-radius: 12rpx;
  -webkit-border-radius: 12rpx;
  background: #00cc76;
}
.fixedBtn span:nth-child(2) {
  margin-left: 38rpx;
}
.noData {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  z-index: 4;
  background: white;
}
.noData img {
  position: absolute;
  display: block;
  width: 300rpx;
  height: 300rpx;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
.timeOver {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  z-index: 3;
}

.imgOver {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 418rpx;
  height: 400rpx;
}

.imgOver img {
  width: 418rpx;
  height: 284rpx;
  position: relative;
}

.confirmBtn {
  display: inline-block;
  padding: 10rpx 20rpx;
  background: #f7b552;
  border-radius: 10rpx;
  position: absolute;
  width: 180rpx;
  text-align: center;
  bottom: 0px;
  left: 50%;
  font-size: 36rpx;
  text-align: center;
  color: white;
  margin-left: -100rpx;
  letter-spacing: 5rpx;
}

@-webkit-keyframes slideInDown {
  from {
    -webkit-transform: translate3d(0, -200%, 0), scale3d(0.3, 0.3, 0.3);
    transform: translate3d(0, -200%, 0), (0.3, 0.3, 0.3);
    visibility: visible;
  }
  to {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}

@keyframes slideInDown {
  from {
    -webkit-transform: translate3d(0, -200%, 0);
    transform: translate3d(0, -200%, 0);
    visibility: visible;
  }
  to {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}

.slideInDown {
  -webkit-animation-name: slideInDown;
  animation-name: slideInDown;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
</style>

